import { spawn } from 'node:child_process'
import { PROJECT_ROOT } from './PROJECT_ROOT.ts'

export const runCommand = async (
  command: string,
  args: string[],
  { cwd }: { cwd: string },
): Promise<void> => {
  await new Promise<void>((resolve, reject) => {
    const child = spawn(command, args, {
      cwd,
      stdio: 'inherit',
      // use shell to handle path separators in Windows
      shell: true,
    })

    child.on('close', (code) => {
      if (code === 0) resolve()
      else reject(new Error(`${command} ${args.join(' ')} exited with code ${code}`))
    })

    child.on('error', reject)
  })
}

export const runCheckFix = async () => {
  await runCommand('pnpm', ['lint:fix'], {
    cwd: PROJECT_ROOT,
  })
}
